﻿Imports Newtonsoft.Json
Imports Newtonsoft.Json.JsonObjectAttribute
Public Class Baidu : Implements InterfaceTransfer
    Private Const URL As String = "http://api.fanyi.baidu.com/api/trans/vip/translate"
    Private Const APP_ID As String = "20211029000985737"
    Private Const APP_KEY As String = "FKDv7otOwshBA1fP3wSM"
    Public Function trans(q As String, from_code As String, to_code As String) As String Implements InterfaceTransfer.trans
        Try
            Dim helper As New HttpHelp
            Dim rdn As New Random
            'Dim salt = CStr(rdn.Next(1000, 9999))
            Dim salt = CStr(6442)
            Dim par As String
            Dim sign As String = buildSign(q, salt)

            par = "q=" & System.Web.HttpUtility.UrlEncode(q, Text.Encoding.UTF8) & "&appid=" & APP_ID & "&salt=" & salt & "&from=" & from_code & "&to=" & to_code & "&sign=" & sign
            Dim result As String = helper.AllGETHttpRequest(URL, par)
            Dim ret As Object = CType(JsonConvert.DeserializeObject(result), Object)
            Dim r As String = ""
            If ret("trans_result") IsNot Nothing Then
                Dim temp = ret("trans_result")
                For i = 0 To temp.count - 1
                    r &= temp(i)("dst")
                Next
            End If
            Return r
        Catch ex As Exception
            Return ex.Message
        End Try
    End Function


    Private Function buildSign(ByVal q As String, ByVal salt As String) As String
        Dim str As String
        str = APP_ID & q & salt & APP_KEY
        Dim md5 As New Md5
        Dim ret = md5.getMd5Hash(str)
        Return ret
    End Function

End Class
